import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router";
import store from "@/store";
import { Tool } from "@/util/tool";
const Index = () => import('../views/index.vue');
const Doc = () => import('../views/doc/doc.vue');
const AdminUser = () => import('../views/admin/User/index.vue');
const AdminEbook = () => import('../views/admin/Ebook/index.vue');
const AdminCategory = () => import('../views/admin/Category/index.vue');
const AdminDoc = () => import('../views/admin/Doc/Index.vue');
const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: '/index'
  },
  {
    path: "/index",
    name: "Index",
    component: Index,
  },
  {
    path: "/doc",
    name: "Doc",
    component: Doc
  },
  {
    path: "/admin/user",
    name: "AdminUser",
    component: AdminUser,
    meta: {
      loginRequire: true,
    },
  },
  {
    path: "/admin/ebook",
    name: "AdminEbook",
    component: AdminEbook,
    meta: {
      loginRequire: true,
    },
  },
  {
    path: "/admin/category",
    name: "AdminCategory",
    component: AdminCategory,
    meta: {
      loginRequire: true,
    },
  },
  {
    path: "/admin/doc",
    name: "AdminDoc",
    component: AdminDoc,
    meta: {
      loginRequire: true,
    },
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

// 路由登录拦截
router.beforeEach((to, from, next) => {
  // 要不要对meta.loginRequire属性做监控拦截
  if (
    to.matched.some(function(item) {
      return item.meta.loginRequire;
    })
  ) {
    const loginUser = store.state.user;
    if (Tool.isEmpty(loginUser)) {
      next("/");
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
